//排班类型为医生
var schedu_type='2';
$(document).ready(function(){
	commonSet();
	//加载查询条件
	initQueryCondition();
	//表格初始化
	initTable();
	//事件绑定
	eventBind();
});

function commonSet(){
	initLoader();
	initDatePickers();
}

//事件绑定
function eventBind(){
	//带有分页信息的查询
	$("#queryBtn").click(query);
	
	//添加按钮弹出层
	$("#addBtn").click(showAddFormDialog);
}

//加载查询条件
function initQueryCondition(){
	//设置起始结束日期
	var now=new Date();
	var nowAfter1month=$.dateAdd(now,'month',1);
	$("input[name='start_date']").val($.dateFormat(now, "yyyy-MM-dd"));
	$("input[name='end_date']").val($.dateFormat(nowAfter1month, "yyyy-MM-dd"));
	
	//科室医生下拉框
	$.getApiClient('/scheduling/depts').get().done(function(data){
		if(!data.payload){
			data.payload=[];
		}
	    multipleSelectData("schedu_did",[{"id": "", "department_name": "请选择"}].concat(data.payload), null, {valueAttr:'id', displayAttr:'department_name'},"请选择");
		$('#schedu_did').multipleSelect({width:'100%', single: true});
	});
	
	
	$('#schedu_did').change(function(){
		var deptId=$(this).children('option:selected').val();
		loadDoctorSelect(deptId);
	}).change();
	
	function loadDoctorSelect(deptId){
		if(deptId){
			$.getApiClient('/scheduling/doctors').setQuery({department_id:deptId}).get().done(function(data){
				if(!data.payload){
					data.payload=[];
				}
			    multipleSelectData("doc_id",[{"id": "", "user_name": "请选择"}].concat(data.payload), null, {valueAttr:'id', displayAttr:'user_name'},"请选择");
				$('#doc_id').multipleSelect({width:'100%', single: true});
			});
		}else{
			multipleSelectData("doc_id",[{"id": "", "user_name": "请选择"}], null, {valueAttr:'id', displayAttr:'user_name'},"请选择");
			$('#doc_id').multipleSelect({width:'100%', single: true});
		}
	}
}

//表格初始化
function initTable(){
	query();
}

//排班列表查询
function query(){
	var queryCondition=$.extend({schedu_type:schedu_type},$("#queryForm").collect());
	
	$.getApiClient('/scheduling').setQuery(queryCondition).get().done(function(data){
		var tableData=groupSchedu(data);
		$('#scheduListTable').bootstrapTable({
			onExpandRow: function (index, row, $detail) {
	          buildSubTable($detail, row.subData);
	      }
		});
		
		$('#scheduListTable').bootstrapTable('load',tableData);
	});
};

//排班数据分组处理
function groupSchedu(scheduData){
	var map = {}, destArry = [];
	//按照排班医生ID+排班日期分组
	$.each(scheduData,function(index,item){
			var key=item.doc_id+'||'+item.schedu_date;
		    if(!map[key]){
		    	destArry.push({
		    		doc_id: item.doc_id,
		    		schedu_date: item.schedu_date,
		            subData: [item]
		        });
		        map[key] = item;
		    }else{
		        for(var i = 0; i < destArry.length; i++){
		            var di = destArry[i];
		            if((di.doc_id+'||'+di.schedu_date) == key){
		            	di.subData.push(item);
		                break;
		            }
		        }
		    }
	})
	
	$.each(destArry,function(index,item){
		//todo 排序
		var subItem=item.subData[0];
//		item.schedu_hid=subItem.schedu_did;
		item.schedu_hname=subItem.schedu_hname;
//		item.schedu_did=subItem.schedu_did;
		item.schedu_dname=subItem.schedu_dname;
		item.doc_name=subItem.doc_name;
	})
	return destArry;
}

//创建子表格
function buildSubTable($detail,subTableData){
	var subTable = $detail.html('<table></table>').find('table');
	subTable.bootstrapTable({
		pagination : false,
		columns :[
			{
				field : 'schedu_start',
				title : '排班开始时间',
				align : 'left',
				valign : 'middle',
				width : '20%'
			}, {
				field : 'schedu_end',
				title : '排班结束时间',
				align : 'left',
				valign : 'middle',
				width : '20%'
			}, {
				field : 'schedu_num',
				title : '号源数',
				align : 'left',
				valign : 'middle',
				width : '20%'
			},{
				field : 'update_time',
				title : '更新时间',
				align : 'left',
				valign : 'middle',
				formatter : timeFormatter,
				width : '20%'
			}, {
				field : 'operation',
				title : '操&nbsp;作',
				align : 'center',
				valign : 'middle',
				width : '20%',
				formatter : subOperateFormatter,
				events : subOperateEvents
			}          
		],
		data: subTableData
	})
}

//新增排班弹出
function showAddFormDialog(){
	customRemoteUrlDialog('新增排班','/page/business/scheduling/doctor/form?type=add',null);
}

//修改排班弹出
function showEditFormDialog(row){
	customRemoteUrlDialog('修改排班','/page/business/scheduling/doctor/form?type=edit&scheduId='+row.id,null);
}

//删除排班弹出
function showDelFormDialog(row){
	customConfirmDialog('是否确认删除该排班？','删除排班',null,function(dialog){
		//执行删除
		dialog.close();
		doDeleteSchedu(row.id,function(data){
			if(data.code == "0"){
				customTimeOutDialog('信息提示','删除排班成功',null,2000);
				query();
			}else{
				customAlertDialog(data.message, '错误提示', null, null);
			}
		})
	});
	
	function doDeleteSchedu(scheduId,callBack){
		$.getApiClient('/scheduling/{scheduId}').setQuery({
			scheduId : scheduId
		}).del().done(function(data){
			callBack(data)
		});
	}
}

//操作列
function subOperateFormatter(value, row, index) {
	return [
	        '<a class="edit" href="javascript:void(0)" title="修改"><i class="fa fa-edit"></i>修改</a>',
	        '&nbsp;&nbsp;&nbsp;',
	        '<a class="delete" href="javascript:void(0)" title="删除"><i class="fa fa-close"></i>删除</a>'
	    ].join('');
};

subOperateEvents = {
	'click .edit' : function(e, value, row, index) {
		showEditFormDialog(row);
	},
	'click .delete' : function(e, value, row, index) {
		showDelFormDialog(row);
	}
};